package com.sheep.advanceddemo.service.impl;

import com.sheep.advanceddemo.entity.SysRole;
import com.sheep.advanceddemo.entity.SysUser;
import com.sheep.advanceddemo.mapper.SysRoleMapper;
import com.sheep.advanceddemo.mapper.SysUserMapper;
import com.sheep.advanceddemo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void save(SysUser sysUser) {
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        sysUserMapper.save(sysUser);
    }

    @Override
    public List<SysUser> findAll() {
        return sysUserMapper.findAll();
    }

    @Override
    public Map<String, Object> getRolesByUser(Integer uid) {
        List<SysRole> allRoles = sysRoleMapper.findAll();
        List<Integer> hasRoles = sysUserMapper.getRolesIdByUserId(uid);
        Map<String, Object> map = new HashMap<>();
        map.put("allRoles", allRoles);
        map.put("hasRoles", hasRoles);
        return map;
    }

    @Override
    public void addRolesToUser(Integer uid, Integer[] rids) {
        sysUserMapper.removeRolesIdByUserId(uid);
        if (rids != null) {
            for (Integer rid : rids) {
                sysUserMapper.addRoleIdByUserId(uid, rid);
            }
        }
    }
}